package middleware

import (
    "gitee.com/zwx784533/zwx2018/app"
    "gitee.com/zwx784533/zwx2018/model"
    "github.com/garyburd/redigo/redis"
    "strings"
    "strconv"
    "time"
)

func GlobalHandle(c *app.Context)  {
    // todo
    c.Next()
}

func LoginHandle(c *app.Context)  {
    // todo
    routePath := c.Request.URL.Path
    // 如果不是 登录 路由，要检查 token
    if routePath != "/admin/login" {
        token := c.Request.Header.Get("token")
        uid := CheckToken(token)
        if uid <= 0 {
            c.ErrorResponse(401, "尚未登录或登录已过期")
            return
        }
        c.Uid = uid
    }

    c.Next()
}

func CheckToken(token string) int  {
    pool, err := model.GetRedisPool("user")
    if err != nil {
        go app.Error(err)
        return 0
    }

    rc := pool.Get()
    defer rc.Close()
    tokenData, err := redis.String(rc.Do("get", "token_"+token))

    if err != nil {
        go app.Error(err)
        return 0
    }

    if tokenData == "" {
        return -1 // 无效的token
    }

    arr := strings.Split(tokenData,"|")
    if len(arr) != 2 {
        return -1 // 无效的token
    }
    var uid int
    var createTime int
    if uid, err = strconv.Atoi(arr[0]); err != nil {
        return -1 // 无效的token
    }

    if createTime, err = strconv.Atoi(arr[1]); err != nil {
        return -1
    }

    if time.Now().Unix() - int64(createTime) > 86400 {
        return -2 // token 过期
    }
    return uid

}
